package com.ynet.middleground.contract.model;

import java.time.LocalDateTime;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynet.middleground.contract.bean.EnterpriseBaseReqObj;
import com.ynet.middleground.contract.constant.OperationTypeEnum;
import com.ynet.middleground.contract.dao.TemplateOperationLogMapper;
import com.ynet.middleground.contract.entity.Template;
import com.ynet.middleground.contract.entity.TemplateOperationLog;
import com.ynet.middleground.user.dto.UserInfoDto;

/**
 * @author liulx
 * @description 模板操作日志记录
 * @date 2020-04-05 20:44
 */
@Component
public class TemplateOperationLogModel extends ServiceImpl<TemplateOperationLogMapper, TemplateOperationLog> {

    @Autowired
    UserCenterModel userCenterModel;

    /**
     * 插入操作模板日志
     * 
     * @param template 当前操作模板对象
     * @param operationTypeEnum 操作类型
     * @param req 带所属企业机构 id 基础请求信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertOperationLog(Template template, OperationTypeEnum operationTypeEnum, EnterpriseBaseReqObj req) {
        TemplateOperationLog log = new TemplateOperationLog();
        log.setTemplateId(template.getId());
        log.setTemplateName(template.getName());
        log.setTemplateType(template.getType());
        log.setOperationType(String.valueOf(operationTypeEnum.getCode()));
        log.setChannel(req.getChannel());
        log.setGmtCreate(LocalDateTime.now());
        log.setCreateBy(req.getOperationUserId());
        log.setGmtModified(LocalDateTime.now());
        log.setModifiedBy(req.getOperationUserId());
        // 查询用户账号信息
        UserInfoDto userInfo = userCenterModel.getUserInfo(req.getOperationUserId(), req.getChannel(),
            req.getOperationUserId(), req.getEnterpriseId());
        String userAccount = userInfo.getUserBaseInformationDto().getUserAccounts();
        log.setOperatorName(userInfo.getUserBaseInformationDto().getUserName());
        log.setOperatorAccount(userAccount);
        // 查询该用户到该类型累计次数
        QueryWrapper<TemplateOperationLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("max(totalize) totalize").eq("operator_account", userAccount).eq("operation_type",
            operationTypeEnum.getCode());
        Map<String, Object> resultMap = this.getMap(queryWrapper);
        if (resultMap != null && resultMap.containsKey("totalize")) {
            int totalize = Integer.parseInt(String.valueOf(resultMap.get("totalize")));
            log.setTotalize(totalize + 1);
        } else {
            log.setTotalize(1);
        }
        this.save(log);
    }

}
